package com.yudaxian.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yudaxian.common.HoneyLogs;
import com.yudaxian.common.enums.LogType;
import com.yudaxian.common.vo.Result;
import com.yudaxian.sys.entity.Alarm;
import com.yudaxian.sys.service.impl.AlarmServiceImpl;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yudaxian
 * @since 2023-12-07
 */
@RestController
@RequestMapping("/alarm")
public class AlarmController {


    @Resource
    private AlarmServiceImpl alarmService;

    @GetMapping("/all")
    public Result<List<Alarm>> getAllAlarms() {
        List<Alarm> Alarms = alarmService.list();
        return Result.success(Alarms);
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getAlarmList(
            @RequestParam(value = "alarmEquipment", required = false) String alarmEquipment,
            @RequestParam(value = "pageNo") Integer pageNo,
            @RequestParam(value = "pageSize") Integer pageSize) {

        LambdaQueryWrapper<Alarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(alarmEquipment), Alarm::getAlarmEquipment, alarmEquipment);

        Page<Alarm> page = new Page<>(pageNo, pageSize);
        alarmService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @HoneyLogs(operation = "项目", type = LogType.ADD)
    @PostMapping("/add")
    //RequestBody，json转Alarm对象，前端输入数据，传给后台json，再转成对象，存入数据库
    public Result<?> addAlarm(@RequestBody Alarm alarm) {
        alarmService.addAlarm(alarm);
        return Result.success("新增传感器成功");
    }

    @HoneyLogs(operation = "项目", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result<?> updateAlarm(@RequestBody Alarm alarm) {
        alarmService.updateAlarm(alarm);
        return Result.success("修改成功");
    }

    @GetMapping("{id}")
    public Result<Alarm> getAlarmById(@PathVariable("id") Integer id) {
        Alarm Alarm = alarmService.getAlarmById(id);

        return Result.success(Alarm);
    }

    @HoneyLogs(operation = "项目", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteAlarmById(@PathVariable("id") Integer id) {
        alarmService.deleteAlarmById(id);

        return Result.success("删除成功");
    }
    
}
